package main

import (
	"context"
	"strings"

	ocontext "golang.org/x/net/context"

	"github.com/go-kit/kit/endpoint"
	"github.com/go-kit/kit/transport/grpc"
)

type StringService interface {
	Uppercase(context.Context, string) (string, error)
	Lowercase(context.Context, string) (string, error)
}

type stringService struct{}

func (this *stringService) Uppercase(ctx context.Context, s string) (string, error) {
	return strings.ToUpper(s), nil
}

func (this *stringService) Lowercase(ctx context.Context, s string) (string, error) {
	return strings.ToLower(s), nil
}

/////////////////////////////////////////////////////
////////// grpc

type grpcStringService struct {
	uppercase grpc.Handler
	lowercase grpc.Handler
}

func (this *grpcStringService) Uppercase(ctx ocontext.Context, r *StringRequest) (*StringResponse, error) {
	_, rsp, err := this.uppercase.ServeGRPC(ctx, r)
	if err != nil {
		return nil, err
	}
	return rsp.(*StringResponse), nil
}

func (this *grpcStringService) Lowercase(ctx ocontext.Context, r *StringRequest) (*StringResponse, error) {
	_, rsp, err := this.lowercase.ServeGRPC(ctx, r)
	if err != nil {
		return nil, err
	}
	return rsp.(*StringResponse), nil
}

func NewGRPCStringService(uppercase endpoint.Endpoint, lowercase endpoint.Endpoint) GRPCStringServer {
	return &grpcStringService{
		uppercase: grpc.NewServer(uppercase, decodeRequest, encodeResponse),
		lowercase: grpc.NewServer(lowercase, decodeRequest, encodeResponse),
	}
}
